package com.example.private_auto_install.ftpGIt;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.*;
import java.util.List;

/**
 * @Description: 文件基本操作
 * @Author: by
 * @Date: 2022-02-19
 **/
public class UtilFile {


    public static void main(String[] args) {
        String url = "http://192.168.10.200:7777/privateTar/fzinstallSJ-1004L.zip"; // 文件下载URL
        String localFilePath = "G:\\临时资料\\largefile.zip"; // 本地文件路径

//        UtilFile.downloadFile(url, localFilePath);
    }

    /**
     * 获取文件后缀的方法
     *
     * @param file 要获取文件后缀的文件
     * @return 文件后缀
     */
    public static String getFileExtension(File file) {
        String extension = "";
        try {
            if (file != null && file.exists()) {
                String name = file.getName();
                extension = name.substring(name.lastIndexOf(".") + 1);
            }
        } catch (Exception e) {
            extension = "";
        }
        return extension;
    }

    /**
     * @描述 获取文件名称
     * @Param file
     * @返回值 java.lang.String
     * @创建人-时间 by - 2022/2/19
     */
    public static String getFileName(File file) {
        String fName = file.getName().trim();
        String fileName = fName.substring(0, fName.lastIndexOf("."));
        return fileName;
    }

    /**
     * @描述 读取json文件
     * @Param fileName
     * @返回值 java.lang.String
     * @创建人-时间 by - 2022/2/22
     */
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString()
                    .replace(" ", "")
                    .replace("\ufeff", "")
                    .replace("\uFEFF", "")
                    .replaceAll("[\\s\\t\\n\\r]", "")
                    .trim();
            if (jsonStr.startsWith("\uFEFF")) {
                jsonStr = jsonStr.replace("\uFEFF", "");
            } else if (jsonStr.endsWith("\uFEFF")) {
                jsonStr = jsonStr.replace("\uFEFF", "");
            }
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * @描述 依据后缀修改type
     * @Param extension
     * @返回值 java.lang.String
     * @创建人-时间 by - 2022/2/19
     */
    public static String changeType(String extension) {
        String type = "";
        switch (extension) {
            case "webp":
                type = "image";
                break;
            case "jpg":
                type = "image";
                break;
            case "png":
                type = "image";
                break;
            case "json":
                type = "json";
                break;
            case "mp3":
                type = "sound";
                break;
            case "wav":
                type = "sound";
                break;
            case "exml":
                type = "text";
                break;
            case "ogg":
                type = "sound";
                break;
            case "fnt":
                type = "json";
                break;
            //你可以有任意数量的case语句
            default: //可选
                type = "bin";
                break;
        }
        return type;
    }

    /**
     * 获取项目所在路径(包括jar)
     *
     * @return
     */
    public static String getProjectPath() {

        java.net.URL url = UtilFile.class.getProtectionDomain().getCodeSource()
                .getLocation();
        String filePath = null;
        try {
            filePath = java.net.URLDecoder.decode(url.getPath(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (filePath.endsWith(".jar"))
            filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
        File file = new File(filePath);
        filePath = file.getAbsolutePath();
        return filePath;
    }

    /**
     * 获取项目所在路径   如果打出jar包会报错。
     *
     * @return
     */
    public static String getRealPath() {
        String realPath = UtilFile.class.getClassLoader().getResource("").getFile();
        File file = new File(realPath);
        realPath = file.getAbsolutePath();
        try {
            realPath = java.net.URLDecoder.decode(realPath, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return realPath;
    }

    /**
     * 删除目录以文件
     *
     * @param dirFile
     * @return
     */
    public static boolean deleteFile(File dirFile) {
        // 如果dir对应的文件不存在，则退出
        if (!dirFile.exists()) {
            return false;
        }
        if (dirFile.isFile()) {
            return dirFile.delete();
        } else {
            for (File file : dirFile.listFiles()) {
                deleteFile(file);
            }
        }
        return dirFile.delete();
    }


    /**
     * 复制文件
     */
    public static boolean copyFile(String oldPath, String newPath) {
        try {
            File oldFile = new File(oldPath);
            if (!oldFile.exists()) {
                System.out.println("旧文件不存在" + oldPath);
            }
            File file = new File(newPath);

            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            file.createNewFile();

            FileInputStream in = new FileInputStream(oldFile);
            FileOutputStream out = null;

            out = new FileOutputStream(file);


            byte[] buffer = new byte[2097152];
            int readByte = 0;
            while ((readByte = in.read(buffer)) != -1) {
                out.write(buffer, 0, readByte);
            }

            in.close();
            out.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 获取目标下的所有文件
     *
     * @param realpath
     * @param files
     * @return
     */
    public static List<File> getAllFiles(String realpath, List<File> files) {
        File realFile = new File(realpath);
        if (realFile.isDirectory()) {
            File[] subfiles = realFile.listFiles();
            for (File file : subfiles) {
                if (file.isDirectory()) {
                    getAllFiles(file.getAbsolutePath(), files);
                } else {
                    files.add(file);
                }

            }
        }
        return files;
    }


    public static void downloadFile(String urlString, String localFilePath) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        FileOutputStream fos = null;
        BufferedInputStream bis = null;

        try {
            httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(urlString);

            // 执行请求
            response = httpClient.execute(httpGet);

            // 检查响应状态
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();

                // 创建一个文件输出流
                File file = new File(localFilePath);
                fos = new FileOutputStream(file);

                // 使用BufferedInputStream以提高性能
                bis = new BufferedInputStream(entity.getContent());

                // 读取并写入数据
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = bis.read(buffer)) != -1) {
                    fos.write(buffer, 0, bytesRead);
                }

                // 完成后刷新并关闭流
                fos.flush();
                System.out.println("File downloaded successfully: " + file.getAbsolutePath());
            } else {
                System.out.println("Failed to download file. Status code: " + response.getStatusLine().getStatusCode());
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 确保关闭所有流和连接
            try {
                if (bis != null) bis.close();
                if (fos != null) fos.close();
                if (response != null) response.close();
                if (httpClient != null) httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
